package com.sh.caryr.erp.util;

import org.apache.commons.collections.CollectionUtils;

import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.*;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

public class RigeHttp {

    private static String getResponsePage(HttpURLConnection connection) throws Exception {
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
        String inputLine;
        StringBuilder response = new StringBuilder();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        return response.toString();
    }

    /**
     * Post parameters example:
     * RigeHttp.HttpParams param = new RigeHttp.HttpParams();
     * param.put("param_json", param_json)
     */
    public static String postRequest(String url, String cookies, HttpParams postParams) throws Exception {
        String postParamsStr = postParams.toEncodedString();
        System.out.println("Posting to " + url);
        // make sure cookies is turn on
        CookieHandler.setDefault(new CookieManager());
        //URL obj = new URL(url);
        URL obj = new URL(null, url, new sun.net.www.protocol.https.Handler());

        HttpsURLConnection conn = (HttpsURLConnection) obj.openConnection();
        // Acts like a browser
        initConnection(conn);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Length", Integer.toString(postParamsStr.length()));
        conn.setRequestProperty("Cookie", cookies);
        System.out.println(postParamsStr);
        // Send post request
        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        wr.writeBytes(postParamsStr);
        wr.flush();
        wr.close();

        String page = getResponsePage(conn);
        System.out.println(page);
        return page;
    }

    private static void initConnection(HttpURLConnection connection) {
        connection.setUseCaches(false);
        connection.setRequestProperty("User-Agent", "Mozilla/5.0");
        connection.setRequestProperty("Accept", "application/json, text/javascript, */*; q=0.01");
        connection.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
        connection.setRequestProperty("Connection", "keep-alive");
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        connection.setDoOutput(true);
        connection.setDoInput(true);
    }

    public static class HttpParams {

        private Map<String, String> params = new LinkedHashMap<>();

        public HttpParams put(String key, String value) {
            params.put(key, value);
            return this;
        }

        String toEncodedString() throws UnsupportedEncodingException {
            Set<Map.Entry<String, String>> entrySet = params.entrySet();
            if (CollectionUtils.isEmpty(entrySet)) {
                return "";
            }

            StringBuilder result = new StringBuilder();
            for (String key : params.keySet()) {
                result.append("&").append(key).append("=").append(URLEncoder.encode(params.get(key), "UTF-8"));
            }

            return result.toString().substring(1);
        }
    }
}
